package com.ruoyi.web.controller.consumer;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SMSEnum;
import com.ruoyi.common.utils.SmsUtil;
import com.ruoyi.common.utils.UUIDUtils;
import com.ruoyi.consumer.domain.Account;
import com.ruoyi.consumer.domain.ConsumerInfo;
import com.ruoyi.consumer.service.IAccountService;
import com.ruoyi.consumer.service.IConsumerInfoService;
import com.ruoyi.framework.util.RedisCache;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 用户操作Controller
 * 
 * @author ruoyi
 * @date 2020-05-25
 */
@Controller
@Api(tags = "用户模块")
@RequestMapping("/consumer/consumerInfo")
public class ConsumerInfoController extends BaseController
{
    private String prefix = "consumer/consumerInfo";
    
    @Autowired
    private IConsumerInfoService consumerInfoService;
    
    @Autowired
    private IAccountService accountService;
    
    @Autowired
    private RedisCache redisCache;
    
    @RequiresPermissions("consumer:consumerInfo:view")
    @GetMapping()
    public String consumerInfo()
    {
        return prefix + "/consumerInfo";
    }
    
    /**
     * 用户发送验证码 <一句话功能简述> <功能详细描述>
     * 
     * @param telphone
     * @return
     * @see [类、类#方法、类#成员]
     */
    @ApiOperation("发送验证码")
    @ApiImplicitParams({@ApiImplicitParam(name = "telphone", value = "电话号码", required = true)
    
    })
    @PostMapping("/sendCaptcha")
    @ResponseBody
    public AjaxResult sendCaptcha(String telphone)
    {
        
        int randomNum = SmsUtil.createRandomNum5();
        System.out.println(randomNum + "******************");
        
        JSONObject jsonObject = SmsUtil.sendSms(randomNum, telphone, SMSEnum.SMS_LOGIN_ERROR.getMsg());
        //添加验证码至redis
        redisCache.setCacheObject(telphone + randomNum,randomNum, 2, TimeUnit.MINUTES);
        
        String smsCode = jsonObject.getString("Code");
        if ("OK".equals(smsCode))
        {
            return AjaxResult.success();
        }
        
        return AjaxResult.error(jsonObject.toString());
    }
    
    /**
     * 用户注册 <一句话功能简述> <功能详细描述>
     * 
     * @param telphone
     * @param captcha
     * @param password
     * @param repassword
     * @param inCode
     * @return
     * @see [类、类#方法、类#成员]
     */
    @ApiOperation("用户注册")
    @ApiImplicitParams({@ApiImplicitParam(name = "telphone", value = "电话号码", required = true),
        @ApiImplicitParam(name = "captcha", value = "验证码", required = true),
        @ApiImplicitParam(name = "password", value = "密码", required = true),
        @ApiImplicitParam(name = "repassword", value = "再次输入密码", required = true),
        @ApiImplicitParam(name = "inCode", value = "邀请码", required = true)
    
    })
    @PostMapping("/register")
    @ResponseBody
    public AjaxResult register(@RequestParam("telphone") String telphone, @RequestParam("captcha") String captcha,
        @RequestParam("password") String password, @RequestParam("repassword") String repassword,
        @RequestParam("inCode") String inCode, HttpSession session)
    {
        Object sessionCaptcha = session.getAttribute("captcha");
//        redisCache.getCacheList(telphone+captcha);
        
        if (!captcha.equals(sessionCaptcha))
        {
            return AjaxResult.error("验证码错误");
        }
        
        if (!password.equals(repassword))
        {
            return AjaxResult.error("两次密码输入不一样");
        }
        int count = consumerInfoService.selectConsumerInfoContByInCode(inCode);
        
        if (count < 1)
        {
            return AjaxResult.error("邀请码" + inCode + "不存在");
        }
        
        ConsumerInfo consumerInfo = new ConsumerInfo(UUIDUtils.getUUID_32(), telphone, password, inCode);
        count = consumerInfoService.insertConsumerInfo(consumerInfo);
        return toAjax(count);
    }
    
    /**
     * 
     * <邀请码验证> <功能详细描述>
     * 
     * @param inCodes
     * @return
     * @see [类、类#方法、类#成员]
     */
    @ApiOperation("邀请码验证")
    @ApiImplicitParams({@ApiImplicitParam(name = "inCode", value = "邀请码", required = true)})
    @GetMapping("/inCodeValid")
    @ResponseBody
    public AjaxResult inCodeValid(@RequestParam("inCode") String inCode)
    {
        
        if (consumerInfoService.selectConsumerInfoContByInCode(inCode) < 1)
        {
            return AjaxResult.error("邀请码" + inCode + "不存在");
        }
        
        return AjaxResult.success();
    }
    
    /**
     * 
     * <手机密码登录> <功能详细描述>
     * 
     * @param telphone
     * @param password
     * @return
     * @see [类、类#方法、类#成员]
     */
    @ApiOperation("手机密码登录")
    @ApiImplicitParams({@ApiImplicitParam(name = "telphone", value = "电话号码", required = true),
        @ApiImplicitParam(name = "password", value = "密码", required = true)})
    @PostMapping("/plogin")
    @ResponseBody
    public AjaxResult plogin(@RequestParam("telphone") String telphone, @RequestParam("password") String password,
        HttpSession session)
    {
        if (consumerInfoService.selectConsumerInfoList(new ConsumerInfo(telphone, "")).isEmpty())
        {
            return AjaxResult.error("手机号不正确");
            
        }
        List<ConsumerInfo> list = consumerInfoService.selectConsumerInfoList(new ConsumerInfo(telphone, password));
        if (list.isEmpty())
        {
            return AjaxResult.error("密码不正确");
        }
        
        session.setAttribute("consumer", list.get(0));
        return AjaxResult.success();
    }
    
    /**
     * 
     * <手机验证码登录> <功能详细描述>
     * 
     * @param telphone
     * @param password
     * @return
     * @see [类、类#方法、类#成员]
     */
    @ApiOperation("手机验证码登录")
    @ApiImplicitParams({@ApiImplicitParam(name = "telphone", value = "电话号码", required = true),
        @ApiImplicitParam(name = "captcha", value = "验证码", required = true)})
    @PostMapping("/clogin")
    @ResponseBody
    public AjaxResult clogin(@RequestParam("telphone") String telphone, @RequestParam("captcha") String captcha,
        HttpSession session)
    {
        System.out.println(session.getAttribute("captcha") + "******************手机验证码登录"
            + captcha.equals(session.getAttribute("captcha").toString()));
        if (!captcha.equals(session.getAttribute("captcha").toString()))
        {
            return AjaxResult.error("验证码错误");
        }
        List<ConsumerInfo> list = consumerInfoService.selectConsumerInfoList(new ConsumerInfo(telphone));
        if (list.isEmpty())
        {
            return AjaxResult.error("号码未注册");
        }
        
        session.setAttribute("consumer", list.get(0));
        return AjaxResult.success();
    }
    
    /**
     ** 上传身份证 <一句话功能简述> <功能详细描述>
     * 
     * @param file
     * @return
     * @see [类、类#方法、类#成员]
     */
    @PostMapping(value = "/upIdCard", headers = "content-type=multipart/form-data")
    @ApiOperation("上传身份证")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "body", dataType = "file", name = "file", value = "上传身份证", required = true)})
    @ResponseBody
    public AjaxResult upIdCard(@RequestParam("file") MultipartFile file)
    {
        AjaxResult ajax = new AjaxResult();
        
        if (file.isEmpty())
        {
            ajax.error("上传失败，请选择文件");
        }
        
        String fileName = file.getOriginalFilename();
        String filePath = "/Users/itinypocket/workspace/temp/";
        File dest = new File(filePath + fileName);
        try
        {
            file.transferTo(dest);
            ajax.success("上传成功");
        }
        catch (IOException e)
        {
            ajax.error("上传失败");
        }
        return ajax;// "上传失败！";
    }
    
    /**
     * 
     * <提交审核> <功能详细描述>
     * 
     * @param filePath 身份证正反照片路劲 逗号分隔多图
     * @param trueName 姓名
     * @param idCode 身份证号码
     * @param bankCode 银行卡哈
     * @param bankAdr 开户银行
     * @return
     * @see [类、类#方法、类#成员]
     */
    @ApiOperation("提交审核")
    @ApiImplicitParams({@ApiImplicitParam(name = "filePath", value = "照片路劲", required = true),
        @ApiImplicitParam(name = "trueName", value = "姓名", required = true),
        @ApiImplicitParam(name = "idCode", value = "身份证号", required = true),
        @ApiImplicitParam(name = "bankCode", value = "银行卡号", required = true),
        @ApiImplicitParam(name = "bankAdr", value = " 开户银行", required = true)})
    @PostMapping("/subIdCard")
    @ResponseBody
    public AjaxResult subIdCard(String filePath, String trueName, String idCode, String bankCode, String bankAdr,
        HttpSession session)
    {
//        ConsumerInfo consumer =   (ConsumerInfo)session.getAttribute("consumer");
        Account account = new Account(UUIDUtils.getUUID_32(), "72505420232546338a0ea6125d3145b2", filePath, trueName,
            idCode, bankCode, bankAdr);
        
        if (!accountService.subIdCard(account))
        {
            AjaxResult.error("提交失败");
        }
        return AjaxResult.success(account);
    }
    
    @ApiOperation("获取实名认证信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "consumerId", value = "用户id", required = true)})
    @PostMapping("/IdStatus")
    @ResponseBody
    public AjaxResult idStatus(String consumerId)
    {
        Account account = accountService.selectAccountByConsumerId(consumerId);
        if (account == null)
        {
            return AjaxResult.error("用户不存在");
        }
        
        return AjaxResult.success(account);
    }
    
    @ApiOperation("修改密码")
    @PostMapping("/setPassword")
    @ResponseBody
    public AjaxResult setPassword(HttpSession session)
    {
        Object obj = session.getAttribute("consumer");
        if (obj == null)
        {
            return AjaxResult.error("会话失效，请重新登录");
        }
        ConsumerInfo consumer = (ConsumerInfo)obj;
        return AjaxResult.success();
    }
    
}
